﻿using System;
using System.Windows.Forms;

namespace ArtMath.Control
{
    public partial class SliderControl : UserControl
    {
        int oldValue, newValue, defaultValue;
        bool cancel;
        string perMark;
        public event Action<int> RefreshObject;
        public SliderControl(int value, int min, int max, int defaultValue = 0, bool percentage = false)
        {
            InitializeComponent();
            trackBar1.Minimum = min;
            trackBar1.Maximum = max;
            this.defaultValue = defaultValue;
            perMark = percentage ? "%" : string.Empty;
            if (value > max) value = max;
            else if (value < min) value = min;
            trackBar1.Value = oldValue = newValue = value;
            label1.Text = value + perMark;
        }
        public int NewValue
        {
            get { return newValue; }
        }
        void trackBar1_Scroll(object sender, EventArgs e)
        {
            oldValue = trackBar1.Value;
            label1.Text = oldValue + perMark;
            refresh();
        }

        private void SliderControl_Leave(object sender, EventArgs e)
        {
            if (!cancel)
            {
                newValue = oldValue;
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                oldValue = newValue;
                cancel = true;
            }
            return base.ProcessDialogKey(keyData);
        }

        void button1_Click(object sender, EventArgs e)
        {
            trackBar1.Value = oldValue = defaultValue;
            label1.Text = defaultValue + perMark;
            refresh();
        }
        void refresh()
        {
            RefreshObject?.Invoke(oldValue);
        }
    }
}
